<?php

require_once('../inc/utils.php');

function main()
{
	if($_GET['action'] == 'login')
		login();
	else if($_GET['action'] == 'logout')
		logout();
}

/**
	@brief Process an attempted login
 */
function login()
{
	//Get user record
	//This code is theoretically vulnerable to a timing attack to guess valid usernames
	//however this is an acceptable risk as usernames tend to be easily guessable anyway.
	$uname = sanitize_db($_POST['user']);
	$r = dbquery("SELECT * FROM `users` WHERE `name` = '$uname' LIMIT 1");
	if(mysql_num_rows($r) == 0)
	{
		header('Location: index.php?loginfail=1');
		die;
	}
	$u = mysql_fetch_object($r);
	
	//Check password
	if($u->pass == crypt($_POST['pass'], $u->pass))
	{
		$_SESSION['uid']  = $u->uid;
		header('Location: index.php');
	}
	else
	{
		header('Location: index.php?loginfail=1');
		die;
	}
}

/**
	@brief Logs the user out
 */
function logout()
{
	$_SESSION['uid'] = -1;
	
	header('Location: index.php');
}

?>
